﻿using Common.Class;
using Common.Model;
using Microsoft.Data.Sqlite;
using SharpConfig;
using SqlSugar;

namespace BLL
{
    public class ConfigBLL
    {
        /// <summary>
        /// 基础配置
        /// </summary>
        public static ConfigModel Config;

        public static string ConfigFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + @"Config.ini";

        /// <summary>
        /// 数据库类型
        /// </summary>
        public static SqlSugar.DbType DBType { get; set; } = SqlSugar.DbType.Sqlite;

        /// <summary>
        /// 基础数据库连接字符串
        /// </summary>
        public static string DBConfigConnectString { get; set; } = "";

        /// <summary>
        /// 加载配置文件信息
        /// </summary>
        /// <param name="configPath"></param>
        /// <returns></returns>
        public static bool LoadConfig(string configPath = "")
        {
            if (!string.IsNullOrWhiteSpace(configPath))
            {
                ConfigFilePath = configPath;
            }

            string _configValue = string.Empty;

            if (File.Exists(ConfigFilePath))
            {
                _configValue = File.ReadAllText(ConfigFilePath);
            }

            if (string.IsNullOrWhiteSpace(_configValue))
            {
                Config = new ConfigModel();
                SaveConfig();
                return false;
            }
            else
            {
                Configuration _cfg = Configuration.LoadFromString(_configValue);
                Config = _cfg["Base"].ToObject<ConfigModel>();

                _cfg = new Configuration();
                _cfg.Add(Section.FromObject("Base", Config), "基本配置");

                if (_configValue != _cfg.StringRepresentation)
                {
                    SaveConfig();
                }
                return true;
            }

        }

        /// <summary>
        /// 保存配置文件信息
        /// </summary>
        public static void SaveConfig()
        {
            if (string.IsNullOrWhiteSpace(ConfigFilePath))
            {
                return;
            }

            if (Config == null)
            {
                Config = new ConfigModel();
            }

            if (File.Exists(ConfigFilePath))
            {
                File.Delete(ConfigFilePath);
            }

            if (Config == null)
            {
                Config = new ConfigModel();
            }


            Configuration _cfg = new Configuration();
            _cfg.Add(Section.FromObject("Base", Config), "基本配置");
            _cfg.SaveToFile(ConfigFilePath);
        }

        /// <summary>
        /// 初始化基础数据库
        /// </summary>
        public static void InitDB()
        {
            SqlSugarClient db = null;

            if (Config.DBType.ToLower() == "sqlite")
            {
                DBType = SqlSugar.DbType.Sqlite;
                DBConfigConnectString = new SqliteConnectionStringBuilder()
                {
                    DataSource = FileHelper.GetRunPath() + @"\RdpServer.db",
                    Mode = SqliteOpenMode.ReadWriteCreate,
                    //Password = "JLDB"
                }.ToString();
            }
            else if (Config.DBType.ToLower() == "mysql")
            {
                DBType = SqlSugar.DbType.MySql;
                DBConfigConnectString = Config.DBConnectStr;
            }
            else if (Config.DBType.ToLower() == "sqlserver")
            {
                DBType = SqlSugar.DbType.SqlServer;
                DBConfigConnectString = Config.DBConnectStr;
            }
            else
            {
                DBType = SqlSugar.DbType.Odbc;
                DBConfigConnectString = Config.DBConnectStr;
            }


            db = new SqlSugarClient(new ConnectionConfig
            {
                DbType = DBType,//要连接的数据库类型
                ConnectionString = DBConfigConnectString,//数据库链接字符串 
                IsAutoCloseConnection = true
            });

            try
            {
                //如果不存在创建数据库存在不会重复创建 
                db.DbMaintenance.CreateDatabase();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }


            //创建表根据实体类

            db.CodeFirst.InitTables(typeof(RoleModel));
            db.CodeFirst.InitTables(typeof(RoleSessionModel));
            db.CodeFirst.InitTables(typeof(UserModel));
            //if (UserBLL.UserGetFromUserID("admin") == null)
            //{
            //    UserModel _user = new UserModel()
            //    {
            //        ID = SnowFlakeSingle.Instance.NextId(),
            //        UserID = "admin",
            //        UserName = "超级管理员",
            //        Password = "",
            //        IsAdmin = "Y",
            //        DeleteFlag = "N",
            //    };
            //    UserBLL.SysUserAdd(_user);

            //}
            db.CodeFirst.InitTables(typeof(UserRoleModel)); 
            db.CodeFirst.InitTables(typeof(UserSessionLogModel));
            db.CodeFirst.InitTables(typeof(UserLogModel));
        }


    }

    /// <summary>
    /// 基础配置类
    /// </summary>
    public class ConfigModel
    {

        [SharpConfig.Comment("本服务监听端口号")]
        public int[] ServicePort { get; set; } = { 30001 };

        [SharpConfig.Comment("可跨域访问的Web端域名")]
        public string OriginsURL { get; set; } = "https://127.0.0.1:22001|http://localhost:22001";
         
        [SharpConfig.Comment("是否必须在服务器使用127.0.0.1域名访问网站")]
        public bool IsMastLocal { get; set; } = true;

        [SharpConfig.Comment("RSA加密公钥")]
        public string RSAPublicKey { get; set; } = "";

        [SharpConfig.Comment("RSA加密私钥")]
        public string RSAPrivateKey { get; set; } = "";

        /// <summary>
        /// 数据库类型
        /// </summary>
        [SharpConfig.Comment("数据库类型")]
        public string DBType { get; set; } = "SQLite";

        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        [SharpConfig.Comment("数据库连接字符串")]
        public string DBConnectStr { get; set; } = "";


    }


}
